import axios from "axios";
import { Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { getLastDomain } from "@/utils/common";
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/apis' : process.env.VUE_APP_AUTH_API_DOMAIN, // 代理处理
  withCredentials: false, //跨域请求时发送cookies 
  timeout: 5000//请求超时
});

// request interceptor
// 请求拦截
service.interceptors.request.use(
  config => {

    if (store.getters.token) {
      config.headers.Authorization = getToken();
    }

    return config;
  },
  error => {
    //做一些请求错误的事情
    console.log(error); //用于调试 
    return Promise.reject(error);
  }
);

// response interceptor
// 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data;
    console.log(res);
    if (res.code === 777) {
      if (res.code === 777) {
        Message({
          message: "token失效",
          type: "error",
          duration: 1000
        });
        setTimeout(() => {
          sessionStorage.clear();
          window.location.href = getLastDomain();
          return;
        }, 1000);
      }
    }

    return res;
  },
  error => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
